import TronWeb from 'tronweb';

var tron = {
    // localTronWeb() {
    //     if (sessionStorage.LoginPlateForm == "privateKeyLogin") {
    //         return PrivateTronWeb
    //     } else if (sessionStorage.LoginPlateForm == "pluginLogin") {
    //         return tronWeb
    //     }
    // },
    // 钱包插件初始化
    initPlugin() {
        return new Promise(async(resolve, rejects) => {
            // 1. check variable, 检查tronweb是否已经加载
            if (window.tronWeb) {
                let tronWeb = window.tronWeb;
                // 轮询登录状态
                let loginTries = 0
                var loggedIn = await new Promise(res => {
                        var timer = setInterval(() => {
                            if (tronWeb && tronWeb.ready) {
                                clearInterval(timer)
                                res(true)
                            } else {
                                loginTries++
                                if (loginTries > 10) {
                                    clearInterval(timer)
                                    res(false)
                                }
                            }
                        }, 1000)
                    })
                    // 已经安装tronLink但是未登录
                if (!loggedIn) {
                    // this.listenAddressChange()
                    resolve({
                        installed: true,
                        loggedIn: false,
                        isTronPay: !!window.tronPay
                    })
                    return
                }

                // 2. check node connection，检查所需要的API是否都可以连通
                // const nodes = await tronWeb.isConnected();

                // const connected = !Object.entries(nodes).map(([name, connected]) => {
                //     if (!connected) {
                //         console.error(`Error: ${name} is not connected`);
                //     }
                //     return connected;
                // }).includes(false);
                if (true) {
                    // 3. 启动正常 安装
                    // this.listenAddressChange()
                    resolve({
                        installed: true,
                        loggedIn: window.tronPay ? window.tronPay.ready : window.tronWeb.ready,
                        isTronPay: !!window.tronPay
                    })
                    return
                } 
                // else {
                //     console.error(`Error: TRON node is not connected`);
                //     console.error('wait for tronLink');
                //     setTimeout(async() => {
                //         await this.initPlugin();
                //     }, 1000);
                // }

            } else {
                // 如果检测到没有注入tronWeb对象，
                // 轮训1秒钟如果有重新走一遍init正常流程
                // 一秒钟还是没有注入tronweb对象，则抛出未安装插件
                let initTries = 0
                var Inited = await new Promise(res => {
                    var timer = setInterval(() => {
                        if (window.tronWeb) {
                            clearInterval(timer)
                            res(true)
                        } else {
                            initTries++
                            if (initTries > 10) {
                                clearInterval(timer)
                                res(false)
                            }
                        }
                    }, 1000)
                })

                if (Inited) {
                    resolve(await this.initPlugin())
                } else {
                    resolve({
                        installed: false,
                        loggedIn: false,
                        isTronPay: !!window.tronPay
                    })
                }
            }
        })
    },
    // 监听tronlink tronpay钱包切换
    listenAddressChange() {
        setTimeout(() => {
            tronWeb.on('addressChanged', () => {
                setTimeout(() => {
                    let tronWebState = {
                        installed: true,
                        loggedIn: window.tronPay ? window.tronPay.ready : window.tronWeb.ready,
                        isTronPay: !!window.tronPay,
                    }
                    vueObj.$store.dispatch('setTron', tronWebState)
                    vueObj.$root.$children[0].walletLoginVisible = false;
                }, 0)
            });
        }, 0)
    },
    // 由用户自己导入私钥登录账户
    initLocalTronWeb(privateKey) {
        return new Promise(async(resolve, rejects) => {
            const HttpProvider = TronWeb.providers.HttpProvider;

            // var fullNode = new HttpProvider('https://api.trongrid.io');
            // var solidityNode = new HttpProvider('https://api.trongrid.io');
            // var eventServer = 'https://api.trongrid.io/';

            var fullNode = new HttpProvider('https://node.kiwidex.io/fullnode');
            var solidityNode = new HttpProvider('https://node.kiwidex.io/solidity');
            var eventServer = 'https://node.kiwidex.io/eventserver';
            // const fullNode = new HttpProvider('http://192.168.0.15/fullnode');
            // const solidityNode = new HttpProvider('http://192.168.0.15/solidity');
            // const eventServer = 'http://192.168.0.15:18891/';
            const PrivateTronWeb = new TronWeb(
                fullNode,
                solidityNode,
                eventServer,
                privateKey
            );
            PrivateTronWeb.setDefaultBlock('latest');
            // const nodes = await PrivateTronWeb.isConnected();
            // const connected = !Object.entries(nodes).map(([name, connected]) => {
            //     if (!connected) {
            //         console.error(`Error: ${name} is not connected`);
            //     }
            //     return connected;
            // }).includes(false);
            PrivateTronWeb.setPrivateKey(privateKey)
            // if (!connected) {
            //     resolve({
            //         installed: false,
            //         loggedIn: false,
            //         isTronPay: false
            //     })
            //     return;
            // }
            window.PrivateTronWeb = PrivateTronWeb
            resolve({
                installed: false,
                loggedIn: true,
                isTronPay: false
            })
        })
    },
    // initLocalTronWeb(privateKey,isRecursion) {
    //     return new Promise(async(resolve, rejects) => {
    //         const HttpProvider = TronWeb.providers.HttpProvider;

            
    //         // var fullNode,solidityNode,eventServer;
    //         // if(isRecursion){
    //         //     fullNode = new HttpProvider('https://node.kiwidex.io/fullnode');
    //         //     solidityNode = new HttpProvider('https://node.kiwidex.io/solidity');
    //         //     eventServer = 'https://node.kiwidex.io/eventserver';
    //         // }else{
    //         //     fullNode = new HttpProvider('https://api.trongrid.io');
    //         //     solidityNode = new HttpProvider('https://api.trongrid.io');
    //         //     eventServer = 'https://api.trongrid.io/';
    //         // }
    //         const fullNode = new HttpProvider('http://192.168.0.15/fullnode');
    //         const solidityNode = new HttpProvider('http://192.168.0.15/solidity');
    //         const eventServer = 'http://192.168.0.15:18891/';
    //         var PrivateTronWeb = new TronWeb(
    //             fullNode,
    //             solidityNode,
    //             eventServer,
    //             privateKey
    //         );
    //         PrivateTronWeb.setDefaultBlock('latest');
    //         const nodes = await PrivateTronWeb.isConnected();
    //         const connected = !Object.entries(nodes).map(([name, connected]) => {
    //             if (!connected) {
    //                 console.error(`Error:${name} is not conected`);
    //             }
    //             return connected;
    //         }).includes(false);
    //         PrivateTronWeb.setPrivateKey(privateKey)
    //         if (!connected) {
    //             this. initLocalTronWeb(privateKey,true)
    //             // resolve({
    //             //     installed: false,
    //             //     loggedIn: false,
    //             //     isTronPay: false
    //             // })
    //             return;
    //         }
    //         window.PrivateTronWeb = PrivateTronWeb
    //         resolve({
    //             installed: false,
    //             loggedIn: true,
    //             isTronPay: false
    //         })
    //     })
    // },
    sendTrc20Tokens(contract, tokens) {
        return new Promise(async(res, rej) => {
            //绑定合约地址
            let contractObject = await this.localTronWeb().contract().at(contract);
            //转账
            try{
                var output = await contractObject.transfer(this.dexAddress(), tokens).send();
            }catch(e){
                rej(e)
            }

            res({
                result: true,
                transaction: {
                    txID: output
                }
            })
        })
    },
    getTrc20TokenBalance(contract) {
        return new Promise(async(res, rej) => {
            //绑定合约地址
            let contractObject = await this.localTronWeb().contract().at(contract);
            //查余额
            let output = await contractObject.balanceOf(vueObj.$store.state.app.tronAddress).call();
            var balance = output
            if (output.balance) {
                balance = output.balance
            }
            res(parseInt(balance.toString()))
        })
    },
    //获取带宽能量及冻结信息
    async getAccountResources() {
        return await this.localTronWeb().trx.getAccountResources()
    },
    //获取账户信息
    async getAccount() {
        return await this.localTronWeb().trx.getAccount()
    },
    //获取带宽
    async getBandwidth() {
        return await this.localTronWeb().trx.getBandwidth()
    },
    //冻结资产
    async freezeBalance(trx, day, freezeName) {
        var transaction = await this.localTronWeb().transactionBuilder.freezeBalance(this.localTronWeb().toSun(trx), day, freezeName) //冻结
        this.signBroad(transaction);
    },
    //签名广播
    async signBroad(transaction) {
        var signedTransaction = await this.localTronWeb().trx.sign(transaction)
        var broadSuccess = await this.localTronWeb().trx.sendRawTransaction(signedTransaction);
        return broadSuccess
    },
    //转账trx
    async sendTrx(trx, address = this.dexAddress()) {
        return await this.localTronWeb().trx.sendTransaction(address, this.localTronWeb().toSun(trx));
    },
    //转账代币
    async sendTokens(tokenNumber, token, address = this.dexAddress()) {
        return await this.localTronWeb().trx.sendToken(address, tokenNumber, token)
        console.log(this.dexAddress())
    },
    // 含有小数点的代币按照精度转换蒸整数
    intToken(token, decimal) {
        token = Number(token)
        decimal = Number(decimal)
        if (isNaN(token) || isNaN(decimal)) {
            throw Error('token or decimal must be a Number');
            return 0
        }
        let decimalMultiply = [1].concat(new Array(decimal).fill(0));
        decimalMultiply = parseInt(decimalMultiply.join(''))
        return parseInt(token * decimalMultiply)
    },
    // 整数token代币转换成小数点的
    floatToken(token, decimal) {
        token = Number(token)
        decimal = Number(decimal)
        if (isNaN(token) || isNaN(decimal)) {
            throw Error('token or decimal must be a Number');
            return 0
        }
        let decimalMultiply = [1].concat(new Array(decimal).fill(0));
        decimalMultiply = parseInt(decimalMultiply.join(''))
        return parseFloat((token / decimalMultiply).toFixed(decimal))
    },
    dexAddress() {
        return vueObj.$store.state.app.dexAddress
    }

}
window.localTronWeb = tron.localTronWeb;
export default tron